#!/usr/bin/env python
# coding=utf-8

import logging
import datetime
from flask import Blueprint, redirect, request, render_template, url_for, g, flash, session, current_app as app
from flask_login import login_required, logout_user, login_user
from over.model import User, db, Bill
from over.handlers.helper import is_valid_email
from over.handlers import helper
from .forms import RegistrationForm, LoginForm
from over.signals import password_forgot_signal

mod = Blueprint(__name__, 'auth')


@mod.route('/register', methods=['GET', 'POST'])
def register():
    if hasattr(g, 'user') and g.user:
        next = request.args.get('next', url_for('over.handlers.my.order.index'))
        return redirect(next)

    form = RegistrationForm(request.form)

    if request.method == 'GET':
        return render_template('auth/register.html', form=form)

    logger = app.logger

    error = None
    if request.method == 'POST':
        if not form.validate():
            error = '无效的用户名或密码'
            logger.error('invalid user or password: %s', form)
            return render_template('auth/register.html', error=error)

        if not is_valid_email(form.email.data):
            error = u'无效的邮件地址'
            logger.error('invalid email address: %s', form.email.data)
            return render_template('auth/register.html', error=error)

        user = User.get_by_email(form.email.data)
        if user is not None:
            logger.error('email address %s already exist', form.email.data)
            error = u'用户已经存在,是否忘记密码'
            return render_template('auth/register.html', error=error)

        logger.info("new user %s", form.email.data)
        user = User(email=form.email.data, password=form.password.data)
        db.session.add(user)
        db.session.commit()

        helper.notify_new_user(email=form.email.data)
        login_user(user)

        # 查看下,是否下过单,如果没有下单过,则跳转到下单页面
        # if Bill.exist_waiting_pay_bill(user.id):
        #     next = url_for('over.handlers.my.order.checkout')
        # else:
        next = url_for('over.handlers.my.order.index')

        return redirect(next)
    # else:
    #     error = form.errors()

    return render_template('auth/register.html', error=error, form=f)


@mod.route('/login', methods=['GET', 'POST'])
def login():
    if hasattr(g, 'user') and g.user:
        next = request.args.get('next', url_for('over.handlers.my.index.index'))
        return redirect(next)

    form = LoginForm(request.form)
    logger = app.logger

    error = None
    if request.method == 'POST' and form.validate():
        email = form.email.data
        password = form.password.data
        user = User.query.filter_by(email=email).first()
        if user is None:
            logger.error('email {0} not exist'.format(email))
            error = u'用户不存在或密码错误'
        elif not user.is_valid_password(password):
            logger.error('user {0} invalid password {1}'.format(email, password))
            error = u'用户不存在或密码错误'
        else:
            logger.info("user {0} login".format(email))
            login_user(user, remember=form.remember.data)

            next_url = request.args.get('next')
            if next_url:
                logger.info("will redirect to next page {0}".format(next_url))
                return redirect(next_url, code=301)

            return redirect(url_for('over.handlers.my.order.index'), code=301)

    return render_template('auth/login.html', error=error)


@mod.route('/logout')
@login_required
def logout():
    logger = app.logger
    logger.info("user {0} will logout".format(g.user.name))
    logout_user()
    return redirect(url_for('over.handlers.index.index'))


@mod.route('/forgot', methods=['GET', 'POST'])
def forgot():
    logger = app.logger
    if request.method == 'POST':
        email = request.form.get('email')
        user = User.get_by_email(email)
        if user is None:
            flash(u'账号不存在')
            logger.info("user {0} not exists when forgot action".format(email))
            return render_template('auth/forgot.html')

        user.forgot_password()

        password_forgot_signal.send(user)
        return render_template('auth/forgot_send.html', email=email)

    return render_template('auth/forgot.html')


@mod.route('/reset/password/<code>', methods=['GET', 'POST'])
def reset_password(code):
    logger = app.logger
    user = User.get_by_code(code)
    logger.info('user %s', user)
    if user is None:
        flash(u'无效code或code已经过期')
        return redirect(url_for('.forgot'))

    if request.method == 'POST':
        password = request.form.get('password')
        password2 = request.form.get('password2')
        if password != password2:
            error = u'两次密码不一致'
            return render_template('auth/reset.html', error=error, user=user)

        user.password = password
        user.status = User.STATUS_ACTIVATE

        db.session.add(user)
        db.session.commit()

        flash(u'修改密码成功, 请重新登录')
        return redirect(url_for('.login'))

    return render_template('auth/reset.html', user=user)
